package com.congiya.example.app;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.congiya.R;

public class RedirectMain extends Activity {
	
    static final int INIT_TEXT_REQUEST = 0;
    static final int NEW_TEXT_REQUEST = 1;
    
	private String mTextPref;
	
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i("RedirectMain", "called");
        
        setContentView(R.layout.ex_app_redirect_main);

        // Watch for button clicks.
        Button btnClear = (Button)findViewById(R.id.btnClear);
        btnClear.setOnClickListener(mClearListener);
        
        Button btnNew = (Button)findViewById(R.id.btnNew);
        btnNew.setOnClickListener(mNewListener);

        
        if (!loadPrefs()) {
            Intent intent = new Intent(this, RedirectGetter.class);
            startActivityForResult(intent, INIT_TEXT_REQUEST);
        }
    }
	
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		
		Log.i("RedirectMain", "onActivityResult.requestCode:"+requestCode+ ", resultCode : " + resultCode);
		
		// 0
	        if (requestCode == INIT_TEXT_REQUEST) {

	            // If the request was cancelled, then we are cancelled as well.
	        	// 0
	            if (resultCode == RESULT_CANCELED) {
	                finish();

	            } else {
	                loadPrefs();
	            }

	            // 1
	        } else if (requestCode == NEW_TEXT_REQUEST) {

	        	// 0
	            if (resultCode != RESULT_CANCELED) {
	                loadPrefs();
	            }

	        }
	    }
	
	private boolean loadPrefs() {
		
		SharedPreferences preferences = getSharedPreferences("RedirectData", 0);
		mTextPref = preferences.getString("text", null);
		
		Log.i("RedirectMain", "loadPrefs.mTextPref : " + mTextPref);
		
		if(mTextPref != null) {
			
			TextView tv = (TextView)findViewById(R.id.text);
			tv.setText(mTextPref);
			
			return true;
		}
		return false;
	}
	
	private OnClickListener mClearListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			SharedPreferences preferences = getSharedPreferences("RedirectData", 0);
			SharedPreferences.Editor editor = preferences.edit();
			
			editor.remove("text");
			editor.commit();
			
			finish();
		}
		
	};
	
	private OnClickListener mNewListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			
            Intent intent = new Intent(RedirectMain.this, RedirectGetter.class);
            startActivityForResult(intent, INIT_TEXT_REQUEST);
			
		}
		
	};

}
